import { useAdminStore } from "@/store";
import router from "./index";
import { storeToRefs } from "pinia";
const modules = import.meta.glob("../views/**/**.vue");

const whiteUrl = ["/login","/hook", "/provide","/demo", "/vmodel", "/wangeditor", "/fileListUpload", "/fileListUpload2", "/pinia2", "/pinia"]

//顶一个一个动态路由添加方法
 
    router.beforeEach((to) => {

        if (whiteUrl.includes(to.path)) {
            return true
        }
    
        const adminStore = useAdminStore();
        const { token, menus,isRoutesLoaded } = storeToRefs(adminStore);
    
        // let token=sessionStorage.getItem('token');
        if (!token.value) {
            return '/login'
        }
    
        //动态路由实现
    
        //如果已经添加过路由
        if(isRoutesLoaded.value) return;
        
    
        let routerMenus = menus.value.filter(item => item.url); //从pinia取出权限
        console.log(routerMenus);
        routerMenus.forEach(item => {
    
    
            let name = item.url.slice(1, 2).toUpperCase() + item.url.slice(2);
            let  component=modules[`../views/${item.url.slice(1)}/${name}.vue`];
    
            console.log(item.url,`../views/${item.url.slice(1)}/${name}.vue`);
    
            //如组件不存在 加载404组件
            if(!component){
                component=modules[`../views/404.vue`];
            }
     
            router.addRoute("Layout",
                {
                    path: item.url,
                    name,
                    component
                }
            )
    
        })
        isRoutesLoaded.value=true;
     
        return to.fullPath;
    
    
    })
 

